package com.peza.postman.monitor;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.peza.postman.domain.MailRequest;
import com.peza.postman.domain.MailResponse;
import com.peza.postman.mail.MailCenter;


@Component("healthMonitor")
public class HealthMonitor implements TimedMonitor{

	
	private static String TO;
	private static String SUBJECT_OK;
	private static String SUBJECT_NOK;
	private static String FROM;
	private static String POSTMAN_LOCATION;
		
	@Autowired
	private MailCenter mailcenter;

	@Autowired
	private ApplicationContext context;
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	private static String lastGoodResponse = "initialized";
	
	private static int counter = 0;
	
	private int reportInterval;
	
	private static final String POSTMAN = "";
	
	
	
	
	public HealthMonitor(){
		
	}
	
	public HealthMonitor(ApplicationContext context){
		this();
		this.context = context;
		//initMailCenter();
	}
	
	
	public void init(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		logger.debug("running job init");	
		
	}
	
	
	public void execute() throws JobExecutionException {
		logger.debug("running job execute");
		poll();
	}

	
	public void destroy() {
		logger.debug("running job destroy");
		if (counter < reportInterval){
			counter++;
		} else {
			report();
			counter = 0;
		}
	}

	
	
	
	
	private void poll(){
		Boolean success = false;
		String response = null;
		HttpClient http = new HttpClient();
		HttpClientParams httpParams = null;
		if (http.getParams() == null) {
			httpParams = new HttpClientParams();
			http.setParams(httpParams);
		} else {
			httpParams = http.getParams();
		}
		http.setHostConfiguration(HostConfiguration.ANY_HOST_CONFIGURATION);
		HttpMethod method = new GetMethod();
		method.setPath(POSTMAN_LOCATION);
		try {
			int code = http.executeMethod(method);
			if (code == 200){
				response = method.getResponseBodyAsString();
				lastGoodResponse = response;
				success = true;
				logger.info("Last response from postman : \n" + response);
			} else {
				success = false;
				throw new Exception();
			}
		} catch (Exception e) {
			logger.error("Postman failure : " + e.getMessage());
			warn(e);
		}
	}
	
	
	private void warn(Exception e){
		MailRequest mail = new MailRequest();
		Calendar now = Calendar.getInstance();
		mail.setContent("something is wrong with postman. \n\n Last good response:\n" + lastGoodResponse +
						"\n\n Exception is : \n " + e.getMessage());
		mail.setFrom(FROM);
		mail.setSubject(SUBJECT_NOK);
		mail.setTo(TO);
		String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
	    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); 
		logger.info("[" + sdf.format(now.getTime()) + "] Sending warning mail");
		MailResponse response = mailcenter.send(mail);
		logger.info("[" + sdf.format(now.getTime()) + "] Mail sent : " + response.isSuccess());
	}

	
	public void report(){
		MailRequest mail = new MailRequest();
		Calendar now = Calendar.getInstance();
		mail.setContent("Postman looking good. \n\n Last response:\n" + lastGoodResponse);
		mail.setFrom(FROM);
		mail.setSubject(SUBJECT_OK);
		mail.setTo(TO);
		String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
	    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); 
		logger.info("[" + sdf.format(now.getTime()) + "] Sending report mail");
		MailResponse response = mailcenter.send(mail);
		logger.info("[" + sdf.format(now.getTime()) + "] Mail sent : " + response.isSuccess());
	}
	
	
	
	private void initMailCenter(){
		if (mailcenter == null) {
			mailcenter = (MailCenter) context.getBean("mailcenter");
		}
	}
	

	public MailCenter getMailcenter() {
		return mailcenter;
	}


	public void setMailcenter(MailCenter mailcenter) {
		this.mailcenter = mailcenter;
	}

	public ApplicationContext getApplicationContext() {
		return context;
	}

	public void setApplicationContext(ApplicationContext context) {
		this.context = context;
	}
	
	public int getReportInterval() {
		return reportInterval;
	}

	public void setReportInterval(int reportInterval) {
		this.reportInterval = reportInterval;
	}

	public static String getTO() {
		return TO;
	}

	public static void setTO(String tO) {
		TO = tO;
	}

	public static String getSUBJECT_OK() {
		return SUBJECT_OK;
	}

	public static void setSUBJECT_OK(String sUBJECT_OK) {
		SUBJECT_OK = sUBJECT_OK;
	}

	public static String getSUBJECT_NOK() {
		return SUBJECT_NOK;
	}

	public static void setSUBJECT_NOK(String sUBJECT_NOK) {
		SUBJECT_NOK = sUBJECT_NOK;
	}

	public static String getFROM() {
		return FROM;
	}

	public static void setFROM(String fROM) {
		FROM = fROM;
	}

	public static String getPOSTMAN_LOCATION() {
		return POSTMAN_LOCATION;
	}

	public static void setPOSTMAN_LOCATION(String pOSTMAN_LOCATION) {
		POSTMAN_LOCATION = pOSTMAN_LOCATION;
	}


	
}
